package gui;

import gamemngr.GameMngr;
import gamemngr.GameMngr.GameStatus;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Scanner;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

import logic.Country;
import logic.GameMap;
import logic.Player;
import logic.moves.AddSoldierMove;
import logic.moves.AttackMove;
import logic.moves.GameMove;

import network.Client;
import network.ClientThread;
import network.DBInfoMsg;
import network.DisconnectionMsg;
import network.GameHistoryMsg;
import network.InformClients;
import network.NetworkMsg;
import network.RecordsTableMsg;
import network.Type;
import network.WinniningMsg;
import network.UserPropertiesMsg;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseTrackAdapter;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import resources.Configuration;
import resources.images.ImagesPath;
import tutorial.StepZero;
import tutorial.Tutorial;

import Database.ConnectionPool;
import Database.DBException;
import Database.PlayerPlayedGames;

import com.swtdesigner.SWTResourceManager;
public class RiskGUI {

	/* Country Labels */

	private Text textLog;
	private Label CentralCanadaFlagLabel;
	private Label IndonesiaFlagLabel;
	private Label NewGuineaFlagLabel;
	private Label EasternAustraliaFlagLabel;
	private Label WesternAustraliaFlagLabel;
	private Label IcelandFlagLabel;
	private Label GreatBritainFlagLabel;
	private Label NorthernEuropeFlagLabel;
	private Label WesternEuropeFlagLabel;
	private Label SouthernEuropeFlagLabel;
	private Label ScandinaviaFlagLabel;
	private Label UkraineFlagLabel;
	private Label UralFlagLabel;
	private Label SiberiaFlagLabel;
	private Label KamchatkaFlagLabel;
	private Label YakutskFlagLabel;
	private Label IrkutskFlagLabel;
	private Label MongoliaFlagLabel;
	private Label AfghanistanFlagLabel;
	private Label JapanFlagLabel;
	private Label SiamFlagLabel;
	private Label ChinaFlagLabel;
	private Label IndiaFlagLabel;
	private Label MiddleEastFlagLabel;
	private Label MadagascarFlagLabel;
	private Label EastAfricaFlagLabel;
	private Label EgyptFlagLabel;
	private Label NorthAfricaFlagLabel;
	private Label CentralAfricaFlagLabel;
	private Label SouthAfricaFlagLabel;
	private Label PeruFlagLabel;
	private Label BrazilFlagLabel;
	private Label VenezuelaFlagLabel;
	private Label CentralAmericaFlagLabel;
	private Label EasternUSFlagLabel;
	private Label WesternUSFlagLabel;
	private Label EasternCanadaFlagLabel;
	private Label GreenlandFlagLabel;
	private Label WesternCanadaFlagLabel;
	private Label NorthwestTerritoryFlagLabel;
	private Label AlaskaFlagLabel;
	private Label ArgentinaFlagLabel;

	private Label CentralCanadaTextLabel;

	private Label ownedLabel;
	private Label countryLabel;
	private Composite mapComposite;	
	private Label playerStatus;

	protected Composite parent;
	protected Shell shell;
	private GameMngr game = new GameMngr();
	private Image map = new Image(Display.getDefault(),ImagesPath.getImageStream("Risk World2.png"));
	private ImageData originalMapData;
	private Map<Integer,Country> countryColourMap = new HashMap<Integer,Country>();
	private Map<Country,Boundaries> countryBoundariesMap = new HashMap<Country,Boundaries>();
	private Map<Country,Label> countryLabelMap = new HashMap<Country,Label>();
	//private File countryMapFile = new File(Configuration.mapPath);
	private Country selectedCountry;
	private int lightendCountryPixel = -1; 
	private RiskGUI gui = this;
	private Map<Country,Label> countryTextLabelMap = new HashMap<Country,Label>();
	private SaveData saveData;
	private boolean moveRuleOnAttack = false;
	private Map<Color, Image> flagColourImageMap = new HashMap<Color, Image>();
	private static String username="";
	private static String usernameProperties="";
	private String records="";
	private String plGames="";
	private static boolean userInDB=false;
	public static final Color[] playerColours = {
			SWTResourceManager.getColor(216, 47, 43),
			SWTResourceManager.getColor(131, 171, 110),
			SWTResourceManager.getColor(117, 137, 174),
			SWTResourceManager.getColor(211, 211, 78),
			SWTResourceManager.getColor(135, 108, 170),
			SWTResourceManager.getColor(172, 146, 111)
	};

	/* Country Text Labels */
	private Label IndonesiaTextLabel;
	private Label NewGuineaTextLabel;
	private Label EasternAustraliaTextLabel;
	private Label WesternAustraliaTextLabel;
	private Label IcelandTextLabel;
	private Label GreatBritainTextLabel;
	private Label NorthernEuropeTextLabel;
	private Label WesternEuropeTextLabel;
	private Label SouthernEuropeTextLabel;
	private Label ScandinaviaTextLabel;
	private Label UkraineTextLabel;
	private Label UralTextLabel;
	private Label SiberiaTextLabel;
	private Label KamchatkaTextLabel;
	private Label YakutskTextLabel;
	private Label IrkutskTextLabel;
	private Label MongoliaTextLabel;
	private Label AfghanistanTextLabel;
	private Label JapanTextLabel;
	private Label SiamTextLabel;
	private Label ChinaTextLabel;
	private Label IndiaTextLabel;
	private Label MiddleEastTextLabel;
	private Label MadagascarTextLabel;
	private Label EastAfricaTextLabel;
	private Label EgyptTextLabel;
	private Label NorthAfricaTextLabel;
	private Label CentralAfricaTextLabel;
	private Label SouthAfricaTextLabel;
	private Label PeruTextLabel;
	private Label BrazilTextLabel;
	private Label VenezuelaTextLabel;
	private Label CentralAmericaTextLabel;
	private Label EasternUSTextLabel;
	private Label WesternUSTextLabel;
	private Label EasternCanadaTextLabel;
	private Label GreenlandTextLabel;
	private Label WesternCanadaTextLabel;
	private Label NorthwestTerritoryTextLabel;
	private Label AlaskaTextLabel;
	private Label ArgentinaTextLabel;
	private MenuItem actionsMenuRef; // this is bridge over actionsMenu which is final

	String displayType = "";
	private MenuItem actionsMenu;
	public MenuItem newItemMenuItem_1;
	public MenuItem newItemMenuItem_14;
	public MenuItem newItemMenuItem_13;
	private double scaleX = 1;
	private double scaleY = 1;

	private int flagLabelHeight = 30;
	private int textLabelHeight = 12;

	public static final String PLUG_IN = "Plug-In";
	public static final String RCP = "RCP";
	private Composite controlsComposite;
	private Composite logComposite;
	private Button commitButton;
	private Image scaledImg = new Image(Display.getDefault(), map.getImageData());

	public static Display display = Display.getDefault();
	private Tutorial tutorial;
	private boolean isNetwork = false;
	
	public volatile AtomicBoolean updateGUI = new AtomicBoolean(false);
	public volatile AtomicReference<GameMngr> newGameMngr = new AtomicReference<GameMngr>(null);
	public volatile AtomicReference<String> addToLog = new AtomicReference<String>();
	public volatile AtomicReference<String> playerDisconnect = new AtomicReference<String>();
	public static boolean doCloseNetworkDialog = false;
	public static boolean lostNetworkGame = false;

	public RiskGUI(){
		shell = new Shell();
		this.parent =  new Composite(shell, SWT.NONE);
	}

	public RiskGUI(Composite parent){
		shell = new Shell();
		this.parent =  parent;
	}

	public RiskGUI(Composite parent, String displayType){
		shell = new Shell();
		shell = parent.getShell();
		shell.setMaximized(true);
		this.parent =  parent;
		this.displayType = displayType;
	}

	public RiskGUI(Composite parent, Shell shell){
		this.shell = shell;
		this.parent = parent;
	}

	public RiskGUI(GameMngr gameMngr) {
		this();
		this.game = gameMngr;
		this.isNetwork  = true;
	}

	public boolean isPlugin(){
		return (this.displayType.equals(RiskGUI.PLUG_IN));
	}

	public boolean isRCP(){
		return (this.displayType.equals(RiskGUI.RCP));
	}

	private void setLabelBackground(Label label, boolean change){
		if(change){
			label.setBackground(SWTResourceManager.getColor(0, 0, 0));
			label.setForeground(SWTResourceManager.getColor(255, 255, 255));
		}else{
			label.setBackground(null);
			label.setForeground(SWTResourceManager.getColor(0, 0, 0));
		}
		label.update();
	}

	/**
	 * Launch the application
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			RiskGUI window = new RiskGUI();
			window.startGUI();
			//window.loadCountryLabelMap();
			//window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void startGUI(){
		this.open();
		/*if(!isPlugin() && !isRCP()){
			Display d = null;
			try
			{
				d = parent.getDisplay();
			}
			catch(SWTException swtex)
			{
				return;
			}
			while(!this.shell.isDisposed()){
				if(!d.Dispatch()){
					d.sleep();
				}
			}
		}*/
	}

	private void printGameStatus(Country country){
		this.countryLabel.setText(country.getName());
		this.countryLabel.setVisible(true);
		this.ownedLabel.setVisible(true);
		Player owner = game.getMap().getCountries().get(country.getName()).getOwner();
		this.ownedLabel.setText(owner != null ? owner.getPlayerName() : "not occupied");
	}

	private void loadFlagColourImageMap(){
		flagColourImageMap.put(SWTResourceManager.getColor(216, 47, 43), new Image(RiskGUI.display,ImagesPath.getImageStream("redFlag.png")));
		flagColourImageMap.put(SWTResourceManager.getColor(131, 171, 110), new Image(RiskGUI.display,ImagesPath.getImageStream("greenFlag.png")));
		flagColourImageMap.put(SWTResourceManager.getColor(117, 137, 174), new Image(RiskGUI.display,ImagesPath.getImageStream("blueFlag.png")));
		flagColourImageMap.put(SWTResourceManager.getColor(211, 211, 78), new Image(RiskGUI.display,ImagesPath.getImageStream("yellowFlag.png")));
		flagColourImageMap.put(SWTResourceManager.getColor(135, 108, 170), new Image(RiskGUI.display,ImagesPath.getImageStream("purpleFlag.png")));
		flagColourImageMap.put(SWTResourceManager.getColor(172, 146, 111), new Image(RiskGUI.display,ImagesPath.getImageStream("brownFlag.png")));
	}

	private void loadCountryLabelMap(){
		/* Flag Labels */
		countryLabelMap.put(game.getMap().getCountries().get("Central Canada"), CentralCanadaFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Indonesia"), IndonesiaFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Alaska"), AlaskaFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Western Canada"), WesternCanadaFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Central America"), CentralAmericaFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Eastern United States"), EasternUSFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Greenland"), GreenlandFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Northwest Territory"), NorthwestTerritoryFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Eastern Canada"), EasternCanadaFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Western United States"), WesternUSFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Argentina"), ArgentinaFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Brazil"), BrazilFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Peru"), PeruFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Venezuela"), VenezuelaFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Great Britain"), GreatBritainFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Iceland"), IcelandFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Northern Europe"), NorthernEuropeFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Scandinavia"), ScandinaviaFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Southern Europe"), SouthernEuropeFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Ukraine"), UkraineFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Western Europe"), WesternEuropeFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Central Africa"), CentralAfricaFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("East Africa"), EastAfricaFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Egypt"), EgyptFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Madagascar"), MadagascarFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("North Africa"), NorthAfricaFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("South Africa"), SouthAfricaFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Afghanistan"), AfghanistanFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("China"), ChinaFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("India"), IndiaFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Irkutsk"), IrkutskFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Japan"), JapanFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Kamchatka"), KamchatkaFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Middle East"), MiddleEastFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Mongolia"), MongoliaFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Siam"), SiamFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Siberia"), SiberiaFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Ural"), UralFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Yakutsk"), YakutskFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Eastern Australia"), EasternAustraliaFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("New Guinea"), NewGuineaFlagLabel);
		countryLabelMap.put(game.getMap().getCountries().get("Western Australia"), WesternAustraliaFlagLabel);

		/* Text Labels */
		countryTextLabelMap.put(game.getMap().getCountries().get("Central Canada"), CentralCanadaTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Indonesia"), IndonesiaTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Alaska"), AlaskaTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Western Canada"), WesternCanadaTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Central America"), CentralAmericaTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Eastern United States"), EasternUSTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Greenland"), GreenlandTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Northwest Territory"), NorthwestTerritoryTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Eastern Canada"), EasternCanadaTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Western United States"), WesternUSTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Argentina"), ArgentinaTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Brazil"), BrazilTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Peru"), PeruTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Venezuela"), VenezuelaTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Great Britain"), GreatBritainTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Iceland"), IcelandTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Northern Europe"), NorthernEuropeTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Scandinavia"), ScandinaviaTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Southern Europe"), SouthernEuropeTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Ukraine"), UkraineTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Western Europe"), WesternEuropeTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Central Africa"), CentralAfricaTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("East Africa"), EastAfricaTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Egypt"), EgyptTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Madagascar"), MadagascarTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("North Africa"), NorthAfricaTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("South Africa"), SouthAfricaTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Afghanistan"), AfghanistanTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("China"), ChinaTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("India"), IndiaTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Irkutsk"), IrkutskTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Japan"), JapanTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Kamchatka"), KamchatkaTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Middle East"), MiddleEastTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Mongolia"), MongoliaTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Siam"), SiamTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Siberia"), SiberiaTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Ural"), UralTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Yakutsk"), YakutskTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Eastern Australia"), EasternAustraliaTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("New Guinea"), NewGuineaTextLabel);
		countryTextLabelMap.put(game.getMap().getCountries().get("Western Australia"), WesternAustraliaTextLabel);

	}

	private Label getCountryLabel(Country country){
		return this.countryLabelMap.get(country);
	}

	public void updateGUIMap(){
		for(Country country : game.getMap().getCountries().values()){
			Label countryFlagLabel = getCountryLabel(country);
			Label countryTextLabel = getCountryTextLabel(country);
			if(countryFlagLabel != null && countryTextLabel != null){
				countryFlagLabel.setVisible(country.hasOwner());
				countryTextLabel.setVisible(country.hasOwner());

				if(country.hasOwner()){
					if(countryFlagLabel.getImage() != flagColourImageMap.get(country.getOwner().getColour())){
						countryFlagLabel.setImage(flagColourImageMap.get(country.getOwner().getColour()));
					}
					if(countryTextLabel.getText() != String.valueOf(country.getSoldiers())){

						countryTextLabel.setText(String.valueOf(country.getSoldiers()));
					}
				}
			}
			if (!game.getPlayers().isEmpty()){
				playerStatus.setBackground(game.getCurrentPlayer().getColour());
				playerStatus.setVisible(true);
				String stat = game.getCurrentPlayer().getPlayerName() + "\n";
				stat += "You have " + game.getCurrentPlayer().getSoldiers() + " soldiers\n";
				stat += "You have made " + game.getCurrentPlayer().getNumberOfMoves() + " moves\n";
				stat += getPlayerStatusDescription() + "\n";
				playerStatus.setText(stat);

			}
			else{
				playerStatus.setVisible(false);
			}
		}
	}
	private String getPlayerStatusDescription()
	{
		String stat = null;
		switch(game.status)
		{
		case NO_GAME:
			stat = "Create new game or load game";
			break;
		case DIVIDE_SOLDIERS:
			stat = "Add soldiers to your countries";
			break;
		case GAME_PLAY:
			stat = "Attack, Add, Declare or Commit";
			break;
		case MOVE_SOLDIERS:
			stat = "Move soldiers between countries";
			break;
		}
		return stat;
	}
	private Label getCountryTextLabel(Country country) {
		return this.countryTextLabelMap.get(country);
	}

	/**
	 * all the games logics
	 */
	private void runGame() {
		runNetworkGame();
		commitButton.setEnabled(true);
		updateGUIMap();
	}

	/**
	 * 
	 */
	public void runNetworkGame() {
		game.status = GameMngr.GameStatus.DIVIDE_SOLDIERS;
		game.setNumMoveRule(-1);
		game.setMaxReenforcement(Integer.MAX_VALUE);
		game.setLimitMove(true);
		game.divideCountries();
		game.giveMissionsToPlayers();
	}
	
	private void loadCountryMaps(){
		String str = "";
		Scanner scanner = new Scanner(Configuration.mapStream);
		while(scanner.hasNextLine()){
			str = scanner.nextLine();
			if(!str.equals("")){
				String[] line = str.split(":");
				Country country = game.getMap().getCountries().get(line[0]);
				this.countryColourMap.put(Integer.valueOf(line[1]), country);
				if(line.length >= 3){
					String[] boundariesCoord = line[2].split(",");
					this.countryBoundariesMap.put(country, new Boundaries(
							Integer.valueOf(boundariesCoord[0]),
							Integer.valueOf(boundariesCoord[1]),
							Integer.valueOf(boundariesCoord[2]),
							Integer.valueOf(boundariesCoord[3])
					));
				}
			}
		}
	}

	private Country getSelected(MouseEvent arg)
	{
		if(countryColourMap.get(this.scaledImg.getImageData().getPixel(arg.x, arg.y)) != null)
			return game.getMap().getCountry(countryColourMap.get(this.scaledImg.getImageData().getPixel(arg.x, arg.y)).getName());
		else
			return null;
	}

	public void loadGameMngr() {
		game.setMap(new GameMap());
		game.setPlayers(new LinkedList<Player>());	
		game.status = GameMngr.GameStatus.NO_GAME;
		loadFlagColourImageMap();
		loadCountryLabelMap();
		loadCountryMaps();
	}

	private void handleMouseOverCountry(int pixelValue){
		ImageData mapData = (ImageData)this.scaledImg.getImageData().clone();
		if(this.countryColourMap.get(pixelValue) != null){
			Country country = game.getMap().getCountry(this.countryColourMap.get(pixelValue).getName());
			if (country != null)
				printGameStatus(country);
			lightenedCountry(pixelValue, mapData, country);
			if(this.countryColourMap.get(lightendCountryPixel)!=null)
				lightenedCountry(lightendCountryPixel, mapData, game.getMap().getCountry(this.countryColourMap.get(lightendCountryPixel).getName()));
		}else{
			if(this.countryColourMap.get(lightendCountryPixel)!=null)
				lightenedCountry(lightendCountryPixel, mapData, game.getMap().getCountry(this.countryColourMap.get(lightendCountryPixel).getName()));
			this.countryLabel.setVisible(false);
			this.ownedLabel.setVisible(false);
		}
		int white = mapData.palette.getPixel(new RGB(255,255,255));
		mapData.transparentPixel = white;
		mapComposite.setBackgroundImage(new Image(RiskGUI.display,mapData));
	}

	/**
	 * @param pixelValue
	 * @param mapData
	 * @param country
	 */
	private void lightenedCountry(int pixelValue, ImageData mapData,
			Country country) {
		//Boundaries boundaries = this.countryBoundariesMap.get(country);
		//int startX = (boundaries != null ? boundaries.getStartX() : 0);
		//int endX = (boundaries != null ? boundaries.getEndX() : mapData.width);
		//int startY = (boundaries != null ? boundaries.getStartY() : 0);
		//int endY = (boundaries != null ? boundaries.getEndY() : mapData.height);

		int[] lineData = new int[mapData.width];

		for(int y = 0; y < mapData.height; y++){
			mapData.getPixels(0,y,mapData.width,lineData,0);
			for (int x=0; x<lineData.length; x++){
				int pixel = lineData[x];
				if(pixel == pixelValue){
					int red = ((pixel>>16) & 0xff) + 70;
					red = (red > 255)? 255 : red;
					int green = ((pixel>>8) & 0xff) + 70;
					green = (green > 255)? 255 : green;
					int blue = (pixel & 0xff) + 70;
					blue = (blue > 255)? 255 : blue;

					pixel = 255<<24 | red<<16 | green<<8 | blue;
					mapData.setPixel(x, y, pixel);	
				}
			}
		}

		/*for(int x=startX; x<endX; x++ ){
			for(int y=startY; y<endY; y++ ){
				if(mapData.getPixel(x, y) == pixelValue){

					int pixel = mapData.getPixel(x, y);

					int red = (int) (((pixel>>16) & 0xff) + 70);
					red = (red > 255)? 255 : red;
					int green = (int) (((pixel>>8) & 0xff) + 70);
					green = (green > 255)? 255 : green;
					int blue = (int) ((pixel & 0xff) + 70);
					blue = (blue > 255)? 255 : blue;

					pixel = 255<<24 | red<<16 | green<<8 | blue;
					mapData.setPixel(x, y, pixel);
				}
			}
		}*/
	}

	private void handleMouseDown(MouseEvent arg0){
		Country currSelected = getSelected(arg0);
		// if state is clean, mark state selected (even if currently selected is null)
		// if currently selected is null, mark state unselected
		if(game.status == GameStatus.NO_GAME)
			return;
		if(game.status == GameStatus.DIVIDE_SOLDIERS)
			return;
		if(currSelected == null)
		{
			unselectCountry();
			return;
		}
		if(selectedCountry == null)
		{
			selectedCountry = currSelected;
			lightendCountryPixel = scaledImg.getImageData().getPixel(arg0.x, arg0.y);
			lightenedCountry(lightendCountryPixel, scaledImg.getImageData(), selectedCountry);
			return;
		}
		else
		{
			if(currSelected != selectedCountry)
			{			
				boolean isAttack = (game.status == GameStatus.GAME_PLAY);
				isAttack = isAttack && selectedCountry.getOwner() != currSelected.getOwner();
				isAttack = isAttack && selectedCountry.getOwner() == game.getCurrentPlayer();
				isAttack = isAttack && selectedCountry.canAttack();
				isAttack = isAttack && selectedCountry.hasNeighbor(currSelected);
				isAttack = isAttack && (!isNetwork || game.getCurrentPlayer().isMe());
				if(isAttack)
				{
					Label countryLabel1 = getCountryTextLabel(selectedCountry);
					Label countryLabel2 = getCountryTextLabel(currSelected);
					setLabelBackground(countryLabel1, true);
					setLabelBackground(countryLabel2, true);
					AttackDialog attackDialog = new AttackDialog(Display.getCurrent().getActiveShell(), selectedCountry, currSelected, this, game, isNetwork);
					addToLog((String)attackDialog.open());
					updateGUIMap();
					setLabelBackground(countryLabel1, false);
					setLabelBackground(countryLabel2, false);
					unselectCountry();
					//the attack was stopped because of maximum move house rule
					if(moveRuleOnAttack) commit(true); 
					moveRuleOnAttack = false;
					return;
				}
				// LAST MOVE IS BEING MADE
				// Exchange Soldiers is the last move of any player
				boolean doMove = game.status == GameStatus.MOVE_SOLDIERS;
				doMove = doMove && selectedCountry.getOwner() == currSelected.getOwner();
				doMove = doMove && selectedCountry.getOwner() == game.getCurrentPlayer();
				doMove = doMove && selectedCountry.canMove(currSelected);
				doMove = doMove && (!isNetwork || game.getCurrentPlayer().isMe());
				if(doMove)
				{
					Label countryLabel1 = getCountryTextLabel(selectedCountry);
					Label countryLabel2 = getCountryTextLabel(currSelected);
					setLabelBackground(countryLabel1, true);
					setLabelBackground(countryLabel2, true);
					MoveDialog moveDialog = new MoveDialog(Display.getCurrent().getActiveShell(), selectedCountry, currSelected, game, isNetwork);
					String movedRes = (String) moveDialog.open();
					updateGUIMap();
					setLabelBackground(countryLabel1, false);
					setLabelBackground(countryLabel2, false);
					if(movedRes != null)
					{
						addToLog(movedRes);
						if(game.getLimitMove() || selectedCountry.getOwner().CheckMovesRule())
						{
							unselectCountry();
							commit(true);	
						}
					}
					else {
						unselectCountry();
					}

				}
			}
		}
		unselectCountry();
	}

	private void unselectCountry()
	{
		selectedCountry = null;
		lightendCountryPixel = -1;
	}

	/**
	 * Open the window
	 */
	public void open() {
		this.loadCountryMaps();
		createContents();
		this.saveData = new SaveData(this.game, parent.getShell());
		if(isNetwork){
			updateGameMngr(game);
			if(addToLog.get() != null)
				addToLog(addToLog.getAndSet(null));
		}
		if(!isPlugin() && !isRCP()){
			shell.setMaximized(true);
			shell.open();
			shell.layout();
			while (!shell.isDisposed()) {
				if (!display.readAndDispatch())
					display.sleep();
				if(this.updateGUI.get()){
					updateNetworkGui();
					commitButton.setEnabled(true);
				}
				if(this.playerDisconnect.get()!=null){
					if(shell.isDisposed()) return;
					AutoDialogMessegaes.displayFeedbackMsg("Disconnection", this.playerDisconnect.get()+ " disconnected from the game.", shell);
					this.playerDisconnect.set(null);
					this.loadGameMngr();
					this.updateGUIMap();
					if(actionsMenu != null)
						actionsMenu.setEnabled(false);
					if(commitButton != null)
						commitButton.setEnabled(false);
					newItemMenuItem_13.setEnabled(false);
					newItemMenuItem_14.setEnabled(false);
					setUserInDB(false);
					setPlayedPlGames("");
					setRecordsTable("");
					setUsernameProperties("");
					Client.setName("");
					Client.setServerIP("");
				}
				if(NetworkGameDialog.needToUpdate){
					NetworkGameDialog.lock.lock();
					try{
						NetworkGameDialog.updateOpenGames();
					} finally {
						NetworkGameDialog.lock.unlock();
					}
				}
				if(doCloseNetworkDialog){
					if(!NetworkGameDialog.shell.isDisposed())
						NetworkGameDialog.shell.dispose();
					doCloseNetworkDialog = false;
				}
				if(lostNetworkGame){
					lostNetworkGame = false;
					LostGame();
				}
			}
		}
	}
	
	private void LostGame() {
		LostDialog lost = new LostDialog(shell);
		lost.open();
		if(isPlugin() || isRCP()){
			endCurrentGame();
		}else{
			endCurrentGame(actionsMenu, commitButton);
		}
		Client.closeConnection();
	}

	private void updateNetworkGui(){
		GameMngr last = this.game;
		this.updateGUI.compareAndSet(true, false);
		GameMngr temp = this.newGameMngr.getAndSet(null);
		updateGameMngr(temp);
		for(int i=0; i<temp.getPlayers().size(); i++){
			temp.getPlayers().get(i).setColour(playerColours[i]);
			temp.getPlayers().get(i).setGame(getGame());
			temp.getPlayers().get(i).setMe(last.getPlayers().get(i).isMe());
		}
		String log = addToLog.getAndSet(null);
		if(!log.equals("commit")){
			addToLog(log);
		}
		if (isUserInDB()){
			newItemMenuItem_13.setEnabled(true);
			newItemMenuItem_14.setEnabled(true);
		}
		updateGUIMap();
	}

	private int calcTextYPos(int originalY){
		return ((int) ((originalY + textLabelHeight)*scaleY) - textLabelHeight);
	}

	private int calcTextXPos(int originalX){
		return (int) (originalX*scaleX);
	}

	private int calcFlagYPos(int originalY){
		return ((int) ((originalY + flagLabelHeight)*scaleY) - flagLabelHeight);
	}

	private int calcFlagXPos(int originalX){
		return (int) (originalX*scaleX);
	}

	/**
	 * Create contents of the window
	 */
	protected void createContents() {

		Image icon =new Image(RiskGUI.display,ImagesPath.getImageStream("Risk Icon.png"));
		shell.setImage(icon);
		shell.addShellListener(new ShellAdapter() {
			public void shellClosed(final ShellEvent arg0) {
				MessageDialog msg = new MessageDialog(shell,"Exit?",null,"Are you sure you want to exit? all unsaved data will be lost.",MessageDialog.QUESTION,new String[] {"Yes","No"},1);
				if(msg.open()==1){
					arg0.doit = false;
				}
				if(isNetwork)
					Client.sendMsg(new DisconnectionMsg(game.getGameID(), Client.getName()));
				
				try {
					ConnectionPool.closePool();
				} catch (DBException e) {
				}
				
			}
		});
		parent.setBackground(SWTResourceManager.getColor(0, 0, 0));
		parent.setSize(469,468);
		shell.setSize(496, 468);
		shell.setText("Risk");



		if(!isPlugin() && !isRCP()){
			final Menu menu = new Menu(shell, SWT.BAR);
			createMenu(menu);
			shell.setMenuBar(menu);
		}

		ImageData mapData = map.getImageData();
		scaleX = (double)(mapData.width) / (double)(737);
		scaleY = (double)(mapData.height) / (double)(377);
		int white = mapData.palette.getPixel(new RGB(255,255,255));
		mapData.transparentPixel = white;
		this.originalMapData = mapData;

		controlsComposite = new Composite(parent, SWT.NONE);
		controlsComposite.setBackgroundMode(SWT.INHERIT_DEFAULT);

		mapComposite = new Composite(parent, SWT.NONE);
		mapComposite.setRedraw(true);
		mapComposite.setBackgroundImage(new Image(RiskGUI.display,ImagesPath.getImageStream("old.png")));
		mapComposite.addMouseTrackListener(new MouseTrackAdapter() {
			public void mouseHover(MouseEvent arg0) {
				handleMouseOverCountry(scaledImg.getImageData().getPixel(arg0.x, arg0.y));
			}
		});
		mapComposite.addMouseListener(new MouseAdapter() {
			public void mouseDown(MouseEvent arg0) {
				handleMouseDown(arg0);
			}
			public void mouseDoubleClick(MouseEvent e) {
				handleMouseDoubleClick(e);	
			}
		});

		mapComposite.setBackgroundImage(new Image(RiskGUI.display,mapData));
		mapComposite.setBackgroundMode(SWT.INHERIT_DEFAULT);
		mapComposite.setBounds(0, 0, map.getBounds().width, map.getBounds().height);
		controlsComposite.setBounds(0, mapComposite.getBounds().height, mapComposite.getBounds().width, 88);
		controlsComposite.setRedraw(true);


		createCountryLabels();


		if(isRCP()){
			parent.getShell().setSize(map.getBounds().width + 210, map.getBounds().height + controlsComposite.getBounds().height + 65);
		}else{
			parent.setSize(map.getBounds().width, map.getBounds().height + controlsComposite.getBounds().height + 50);
		}
		shell.setSize(map.getBounds().width, map.getBounds().height + controlsComposite.getBounds().height + 50);

		final Label gameStatusLabel = new Label(controlsComposite, SWT.NONE);
		gameStatusLabel.setFont(SWTResourceManager.getFont("Comic Sans MS", 12, SWT.BOLD));
		gameStatusLabel.setAlignment(SWT.CENTER);
		gameStatusLabel.setText("Game Status");
		gameStatusLabel.setBounds(0, 5, 120, 18);

		final Label countryLabel_1 = new Label(controlsComposite, SWT.NONE);
		countryLabel_1.setFont(SWTResourceManager.getFont("Comic Sans MS", 10, SWT.BOLD));
		countryLabel_1.setText("Country:");
		countryLabel_1.setBounds(15, 29, 55, 18);

		countryLabel = new Label(controlsComposite, SWT.NONE);
		countryLabel.setFont(SWTResourceManager.getFont("Comic Sans MS", 10, SWT.BOLD));
		countryLabel.setBounds(75, 29, 130, 18);
		countryLabel.setVisible(false);

		final Label owbedByLabel = new Label(controlsComposite, SWT.NONE);
		owbedByLabel.setFont(SWTResourceManager.getFont("Comic Sans MS", 10, SWT.BOLD));
		owbedByLabel.setBounds(15, 53, 70, 18);
		owbedByLabel.setText("Owned By:");

		ownedLabel = new Label(controlsComposite, SWT.NONE);
		ownedLabel.setFont(SWTResourceManager.getFont("Comic Sans MS", 10, SWT.BOLD));
		ownedLabel.setBounds(90, 53, 130, 18);
		ownedLabel.setVisible(false);

		playerStatus = new Label(controlsComposite, SWT.BORDER);
		playerStatus.setBounds(235, 0, 250, 85);
		playerStatus.setVisible(false);
		playerStatus.setAlignment(SWT.CENTER);
		playerStatus.setFont(SWTResourceManager.getFont("Comic Sans MS", 10, SWT.BOLD));

		final Label logo = new Label(controlsComposite, SWT.NONE);
		logo.setBounds(485, 0, 252, 85);
		logo.setImage(new Image(RiskGUI.display,ImagesPath.getImageStream("logo.png")));

		int shellWidth = shell.getSize().x;
		parent.setSize(shellWidth + 190, shell.getSize().y);
		shell.setSize(shellWidth + 190, shell.getSize().y);

		logComposite = new Composite(parent, SWT.NONE);
		logComposite.setBounds(shell.getClientArea().width - 188, 0, 188, shell.getClientArea().height);

		commitButton = new Button(logComposite, SWT.NONE);
		commitButton.setEnabled(false);
		commitButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent arg0) {
				commit(false);
			}	
		}
		);
		commitButton.setText("&Commit");
		commitButton.setBounds(44, logComposite.getClientArea().height - 74, 100, 60);
		commitButton.setFont(SWTResourceManager.getFont("Comic Sans MS", 14, SWT.BOLD));

		textLog = new Text(logComposite, SWT.WRAP | SWT.V_SCROLL | SWT.READ_ONLY | SWT.BORDER);
		textLog.setBounds(0, 25, 188, logComposite.getClientArea().height - 113);

		final Label label = new Label(logComposite, SWT.NONE);
		label.setFont(SWTResourceManager.getFont("Comic Sans MS", 11, SWT.BOLD));
		label.setText("Game Log:");
		label.setAlignment(SWT.CENTER);
		label.setBounds(0, 0, 188, 25);

		shell.addListener (SWT.Resize,  new Listener () {
			public void handleEvent (Event e) {
				scaleShell(shell);
			}
		});

		parent.getParent().addListener (SWT.Resize,  new Listener () {
			public void handleEvent (Event e) {
				scaleShell(parent.getParent());
			}
		});
	}

	protected void scaleShell(Composite shell) {
		parent.setSize(shell.getClientArea().width, shell.getClientArea().height);

		controlsComposite.setBounds(0, shell.getClientArea().height - 88, shell.getClientArea().width-188, 88);
		logComposite.setBounds(shell.getClientArea().width - 188, 0, 188, shell.getClientArea().height);
		textLog.setBounds(0, 25, 188, logComposite.getClientArea().height - 113);
		commitButton.setBounds(44, logComposite.getClientArea().height - 74, 100, 60);

		double ratio = (double)(this.map.getImageData().height) / (double)(this.map.getImageData().width);
		int width = (int)(shell.getClientArea().width-188);
		int height = (int)(width * ratio);
		int startY = (shell.getClientArea().height-88)/2 - height/2;
		mapComposite.setBounds(0, startY, width, height);

		//		mapComposite.setSize(shell.getClientArea().width-188, shell.getClientArea().height-88);

		double scaleX = (double)(mapComposite.getClientArea().width) / (double)(map.getImageData().width);
		double scaleY = (double)(mapComposite.getClientArea().height) / (double)(map.getImageData().height);

		ImageData data = map.getImageData().scaledTo(
				(int) (map.getImageData().width * scaleX), 
				(int) (map.getImageData().height * scaleY));
		scaledImg = new Image(RiskGUI.display, data);
		mapComposite.setBackgroundImage(scaledImg);

		this.scaleX = (double)(mapComposite.getClientArea().width) / 737;
		this.scaleY = (double)(mapComposite.getClientArea().height) / 377;
		initCountryLabels(false);
		updateGUIMap();
	}

	/**
	 * 
	 */
	private void createCountryLabels() {
		ArgentinaTextLabel = new Label(mapComposite, SWT.NONE);
		ArgentinaFlagLabel = new Label(mapComposite, SWT.NONE);
		AlaskaTextLabel = new Label(mapComposite, SWT.NONE);
		AlaskaFlagLabel = new Label(mapComposite, SWT.NONE);
		NorthwestTerritoryTextLabel = new Label(mapComposite, SWT.NONE);
		NorthwestTerritoryFlagLabel = new Label(mapComposite, SWT.NONE);
		WesternCanadaTextLabel = new Label(mapComposite, SWT.NONE);
		WesternCanadaFlagLabel = new Label(mapComposite, SWT.NONE);
		GreenlandTextLabel = new Label(mapComposite, SWT.NONE);
		GreenlandFlagLabel = new Label(mapComposite, SWT.NONE);
		EasternCanadaTextLabel = new Label(mapComposite, SWT.NONE);
		EasternCanadaFlagLabel = new Label(mapComposite, SWT.NONE);
		WesternUSTextLabel = new Label(mapComposite, SWT.NONE);
		WesternUSFlagLabel = new Label(mapComposite, SWT.NONE);
		EasternUSTextLabel = new Label(mapComposite, SWT.NONE);
		EasternUSFlagLabel = new Label(mapComposite, SWT.NONE);
		CentralAmericaTextLabel = new Label(mapComposite, SWT.NONE);
		CentralAmericaFlagLabel = new Label(mapComposite, SWT.NONE);
		VenezuelaTextLabel = new Label(mapComposite, SWT.NONE);
		VenezuelaFlagLabel = new Label(mapComposite, SWT.NONE);
		BrazilTextLabel = new Label(mapComposite, SWT.NONE);
		BrazilFlagLabel = new Label(mapComposite, SWT.NONE);
		PeruTextLabel = new Label(mapComposite, SWT.NONE);
		PeruFlagLabel = new Label(mapComposite, SWT.NONE);
		SouthAfricaTextLabel = new Label(mapComposite, SWT.NONE);
		SouthAfricaFlagLabel = new Label(mapComposite, SWT.NONE);
		CentralAfricaTextLabel = new Label(mapComposite, SWT.NONE);
		CentralAfricaFlagLabel = new Label(mapComposite, SWT.NONE);
		NorthAfricaTextLabel = new Label(mapComposite, SWT.NONE);
		NorthAfricaFlagLabel = new Label(mapComposite, SWT.NONE);
		EgyptTextLabel = new Label(mapComposite, SWT.NONE);
		EgyptFlagLabel = new Label(mapComposite, SWT.NONE);
		EastAfricaTextLabel = new Label(mapComposite, SWT.NONE);
		EastAfricaFlagLabel = new Label(mapComposite, SWT.NONE);
		MadagascarTextLabel = new Label(mapComposite, SWT.NONE);
		MadagascarFlagLabel = new Label(mapComposite, SWT.NONE);
		MiddleEastTextLabel = new Label(mapComposite, SWT.NONE);
		MiddleEastFlagLabel = new Label(mapComposite, SWT.NONE);
		IndiaTextLabel = new Label(mapComposite, SWT.NONE);
		IndiaFlagLabel = new Label(mapComposite, SWT.NONE);
		ChinaTextLabel = new Label(mapComposite, SWT.NONE);
		ChinaFlagLabel = new Label(mapComposite, SWT.NONE);
		SiamTextLabel = new Label(mapComposite, SWT.NONE);
		SiamFlagLabel = new Label(mapComposite, SWT.NONE);
		JapanTextLabel = new Label(mapComposite, SWT.NONE);
		JapanFlagLabel = new Label(mapComposite, SWT.NONE);
		AfghanistanTextLabel = new Label(mapComposite, SWT.NONE);
		AfghanistanFlagLabel = new Label(mapComposite, SWT.NONE);
		MongoliaTextLabel = new Label(mapComposite, SWT.NONE);
		MongoliaFlagLabel = new Label(mapComposite, SWT.NONE);
		IrkutskTextLabel = new Label(mapComposite, SWT.NONE);
		IrkutskFlagLabel = new Label(mapComposite, SWT.NONE);
		YakutskTextLabel = new Label(mapComposite, SWT.NONE);
		YakutskFlagLabel = new Label(mapComposite, SWT.NONE);
		KamchatkaTextLabel = new Label(mapComposite, SWT.NONE);
		KamchatkaFlagLabel = new Label(mapComposite, SWT.NONE);
		SiberiaTextLabel = new Label(mapComposite, SWT.NONE);
		SiberiaFlagLabel = new Label(mapComposite, SWT.NONE);
		UralTextLabel = new Label(mapComposite, SWT.NONE);
		UralFlagLabel = new Label(mapComposite, SWT.NONE);
		UkraineTextLabel = new Label(mapComposite, SWT.NONE);
		UkraineFlagLabel = new Label(mapComposite, SWT.NONE);
		ScandinaviaTextLabel = new Label(mapComposite, SWT.NONE);
		ScandinaviaFlagLabel = new Label(mapComposite, SWT.NONE);
		SouthernEuropeTextLabel = new Label(mapComposite, SWT.NONE);
		SouthernEuropeFlagLabel = new Label(mapComposite, SWT.NONE);
		WesternEuropeTextLabel = new Label(mapComposite, SWT.NONE);
		WesternEuropeFlagLabel = new Label(mapComposite, SWT.NONE);
		NorthernEuropeTextLabel = new Label(mapComposite, SWT.NONE);
		NorthernEuropeFlagLabel = new Label(mapComposite, SWT.NONE);
		GreatBritainTextLabel = new Label(mapComposite, SWT.NONE);
		GreatBritainFlagLabel = new Label(mapComposite, SWT.NONE);
		IcelandTextLabel = new Label(mapComposite, SWT.NONE);
		IcelandFlagLabel = new Label(mapComposite, SWT.NONE);
		WesternAustraliaTextLabel = new Label(mapComposite, SWT.NONE);
		WesternAustraliaFlagLabel = new Label(mapComposite, SWT.NONE);
		EasternAustraliaTextLabel = new Label(mapComposite, SWT.NONE);
		EasternAustraliaFlagLabel = new Label(mapComposite, SWT.NONE);
		NewGuineaTextLabel = new Label(mapComposite, SWT.NONE);
		NewGuineaFlagLabel = new Label(mapComposite, SWT.NONE);
		IndonesiaTextLabel = new Label(mapComposite, SWT.NONE);
		IndonesiaFlagLabel = new Label(mapComposite, SWT.NONE);
		CentralCanadaTextLabel = new Label(mapComposite, SWT.NONE);
		CentralCanadaFlagLabel = new Label(mapComposite, SWT.NONE);

		initCountryLabels(true);
	}

	/**
	 * 
	 */
	private void initCountryLabels(boolean addListeners) {
		initTextLabel(ArgentinaTextLabel, 175, 312, addListeners);
		initFlagLabel(ArgentinaFlagLabel, 171, 292, addListeners);
		initTextLabel(AlaskaTextLabel, 40, 45, addListeners);
		initFlagLabel(AlaskaFlagLabel, 34, 25, addListeners);
		initTextLabel(NorthwestTerritoryTextLabel, 105, 45, addListeners);
		initFlagLabel(NorthwestTerritoryFlagLabel, 100, 25, addListeners);
		initTextLabel(WesternCanadaTextLabel, 85, 75, addListeners);
		initFlagLabel(WesternCanadaFlagLabel, 81, 55, addListeners);
		initTextLabel(GreenlandTextLabel, 265, 32, addListeners);
		initFlagLabel(GreenlandFlagLabel, 261, 12, addListeners);
		initTextLabel(EasternCanadaTextLabel, 185, 75, addListeners);
		initFlagLabel(EasternCanadaFlagLabel, 180, 55, addListeners);
		initTextLabel(WesternUSTextLabel, 75, 112, addListeners);
		initFlagLabel(WesternUSFlagLabel, 70, 92, addListeners);
		initTextLabel(EasternUSTextLabel, 125, 120, addListeners);
		initFlagLabel(EasternUSFlagLabel, 120, 100, addListeners);
		initTextLabel(CentralAmericaTextLabel, 105, 165, addListeners);
		initFlagLabel(CentralAmericaFlagLabel, 100, 145, addListeners);
		initTextLabel(VenezuelaTextLabel, 150, 205, addListeners);
		initFlagLabel(VenezuelaFlagLabel, 144, 185, addListeners);
		initTextLabel(BrazilTextLabel, 205, 258, addListeners);
		initFlagLabel(BrazilFlagLabel, 198, 238, addListeners);
		initTextLabel(PeruTextLabel, 165, 250, addListeners);
		initFlagLabel(PeruFlagLabel, 160, 230, addListeners);
		initTextLabel(SouthAfricaTextLabel, 385, 285, addListeners);
		initFlagLabel(SouthAfricaFlagLabel, 380, 265, addListeners);
		initTextLabel(CentralAfricaTextLabel, 385, 220, addListeners);
		initFlagLabel(CentralAfricaFlagLabel, 380, 200, addListeners);
		initTextLabel(NorthAfricaTextLabel, 325, 175, addListeners);
		initFlagLabel(NorthAfricaFlagLabel, 319, 155, addListeners);
		initTextLabel(EgyptTextLabel, 390, 145, addListeners);
		initFlagLabel(EgyptFlagLabel, 385, 125, addListeners);
		initTextLabel(EastAfricaTextLabel, 414, 190, addListeners);
		initFlagLabel(EastAfricaFlagLabel, 410, 170, addListeners);
		initTextLabel(MadagascarTextLabel, 450, 260, addListeners);
		initFlagLabel(MadagascarFlagLabel, 445, 240, addListeners);
		initTextLabel(MiddleEastTextLabel, 440, 140, addListeners);
		initFlagLabel(MiddleEastFlagLabel, 435, 120, addListeners);
		initTextLabel(IndiaTextLabel, 520, 145, addListeners);
		initFlagLabel(IndiaFlagLabel, 515, 125, addListeners);
		initTextLabel(ChinaTextLabel, 590, 140, addListeners);
		initFlagLabel(ChinaFlagLabel, 585, 120, addListeners);
		initTextLabel(SiamTextLabel, 595, 175, addListeners);
		initFlagLabel(SiamFlagLabel, 590, 155, addListeners);
		initTextLabel(JapanTextLabel, 660, 115, addListeners);
		initFlagLabel(JapanFlagLabel, 655, 95, addListeners);
		initTextLabel(AfghanistanTextLabel, 480, 105, addListeners);
		initFlagLabel(AfghanistanFlagLabel, 475, 85, addListeners);
		initTextLabel(MongoliaTextLabel, 580, 100, addListeners);
		initFlagLabel(MongoliaFlagLabel, 575, 80, addListeners);
		initTextLabel(IrkutskTextLabel, 565, 70, addListeners);
		initFlagLabel(IrkutskFlagLabel, 560, 50, addListeners);
		initTextLabel(YakutskTextLabel, 585, 40, addListeners);
		initFlagLabel(YakutskFlagLabel, 580, 20, addListeners);
		initTextLabel(KamchatkaTextLabel, 660, 40, addListeners);
		initFlagLabel(KamchatkaFlagLabel, 656, 20, addListeners);
		initTextLabel(SiberiaTextLabel, 525, 40, addListeners);
		initFlagLabel(SiberiaFlagLabel, 520, 20, addListeners);
		initTextLabel(UralTextLabel, 475, 50, addListeners);
		initFlagLabel(UralFlagLabel, 470, 30, addListeners);
		initTextLabel(UkraineTextLabel, 420, 65, addListeners);
		initFlagLabel(UkraineFlagLabel, 415, 45, addListeners);
		initTextLabel(ScandinaviaTextLabel, 370, 45, addListeners);
		initFlagLabel(ScandinaviaFlagLabel, 365, 25, addListeners);
		initTextLabel(SouthernEuropeTextLabel, 390, 95, addListeners);
		initFlagLabel(SouthernEuropeFlagLabel, 385, 75, addListeners);
		initTextLabel(WesternEuropeTextLabel, 325, 105, addListeners);
		initFlagLabel(WesternEuropeFlagLabel, 320, 85, addListeners);
		initTextLabel(NorthernEuropeTextLabel, 360, 75, addListeners);
		initFlagLabel(NorthernEuropeFlagLabel, 355, 55, addListeners);
		initTextLabel(GreatBritainTextLabel, 300, 65, addListeners);
		initFlagLabel(GreatBritainFlagLabel, 320, 45, addListeners);
		initTextLabel(IcelandTextLabel, 315, 35, addListeners);
		initFlagLabel(IcelandFlagLabel, 310, 15, addListeners);
		initTextLabel(WesternAustraliaTextLabel, 623, 290, addListeners);
		initFlagLabel(WesternAustraliaFlagLabel, 618, 270, addListeners);
		initTextLabel(EasternAustraliaTextLabel, 685, 285, addListeners);
		initFlagLabel(EasternAustraliaFlagLabel, 680, 265, addListeners);
		initTextLabel(NewGuineaTextLabel, 690, 225, addListeners);
		initFlagLabel(NewGuineaFlagLabel, 684, 205, addListeners);
		initTextLabel(IndonesiaTextLabel, 620, 210, addListeners);
		initFlagLabel(IndonesiaFlagLabel, 615, 190, addListeners);
		initTextLabel(CentralCanadaTextLabel, 137, 70, addListeners);
		initFlagLabel(CentralCanadaFlagLabel, 130, 50, addListeners);
	}

	/**
	 * 
	 */
	private void initFlagLabel(final Label flagLabel, int x, int y, boolean addListeners) {
		int posY;
		int posX;
		posY = calcFlagYPos(y);
		posX = calcFlagXPos(x);
		flagLabel.setBounds(posX, posY, 30, 30);
		flagLabel.setVisible(false);
		flagLabel.setText("0");
		flagLabel.setImage(new Image(RiskGUI.display,ImagesPath.getImageStream("flag.png")));
		if(addListeners){
			flagLabel.addMouseTrackListener(new MouseTrackAdapter() {
				public void mouseHover(MouseEvent arg0) {
					handleMouseOverCountry(scaledImg.getImageData().getPixel(
							flagLabel.getBounds().x + arg0.x, 
							flagLabel.getBounds().y + arg0.y));
				}
			});
			flagLabel.addMouseListener(new MouseAdapter() {
				public void mouseDown(MouseEvent e) {
					e.x += flagLabel.getBounds().x;
					e.y += flagLabel.getBounds().y;
					handleMouseDown(e);
				}
				public void mouseDoubleClick(MouseEvent e) {
					e.x += flagLabel.getBounds().x;
					e.y += flagLabel.getBounds().y;
					handleMouseDoubleClick(e);	
				}
			});
		}
	}

	/**
	 * 
	 */
	private void initTextLabel(final Label textLabel, int x, int y, boolean addListeners) {
		int posY;
		int posX;

		textLabel.setVisible(false);
		posY = calcTextYPos(y);
		posX = calcTextXPos(x);
		textLabel.setBounds(posX, posY, 20, 14);
		textLabel.setAlignment(SWT.CENTER);
		textLabel.setFont(SWTResourceManager.getFont("Arial", 10, SWT.BOLD));
		textLabel.setText("300");
		if(addListeners){
			textLabel.addMouseTrackListener(new MouseTrackAdapter() {
				public void mouseHover(MouseEvent arg0) {
					handleMouseOverCountry(scaledImg.getImageData().getPixel(
							textLabel.getBounds().x + arg0.x, 
							textLabel.getBounds().y + arg0.y));
				}
			});
			textLabel.addMouseListener(new MouseAdapter() {
				public void mouseDown(MouseEvent e) {
					e.x += textLabel.getBounds().x;
					e.y += textLabel.getBounds().y;
					handleMouseDown(e);
				}
				public void mouseDoubleClick(MouseEvent e) {
					e.x += textLabel.getBounds().x;
					e.y += textLabel.getBounds().y;
					handleMouseDoubleClick(e);	
				}
			});
		}
	}

	/**
	 * @param menu
	 */
	public void createMenu(final Menu menu) {
		final MenuItem newSubmenuMenuItem = new MenuItem(menu, SWT.CASCADE);
		newSubmenuMenuItem.setText("&Game");

		final Menu menu_1 = new Menu(newSubmenuMenuItem);
		newSubmenuMenuItem.setMenu(menu_1);

		actionsMenu = new MenuItem(menu, SWT.CASCADE);
		actionsMenuRef = actionsMenu; // bridge over final
		actionsMenu.setEnabled(false);
		actionsMenu.setText("&Actions");

		final MenuItem newItemMenuItem = new MenuItem(menu_1, SWT.NONE);
		newItemMenuItem.setAccelerator(SWT.CTRL | 'N');
		newItemMenuItem.setText("&New\tCtrl+N");
		newItemMenuItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent arg0) {
				newGame();
			}
		});
		final MenuItem onlineMenuItem = new MenuItem(menu_1, SWT.NONE);
		onlineMenuItem.setAccelerator(SWT.CTRL | 'O');
		onlineMenuItem.setText("&Online Game\tCtrl+O");
		onlineMenuItem.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent arg0) {
				onlineGame();
			}
		});
		newItemMenuItem_1 = new MenuItem(menu_1, SWT.NONE);
		newItemMenuItem_1.setEnabled(false);
		newItemMenuItem_1.setAccelerator(SWT.CTRL | 'S');
		newItemMenuItem_1.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				saveGame();
			}
		});
		newItemMenuItem_1.setText("&Save\tCtrl+S");

		final MenuItem newItemMenuItem_2 = new MenuItem(menu_1, SWT.NONE);
		newItemMenuItem_2.setAccelerator(SWT.CTRL | 'L');
		newItemMenuItem_2.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				loadGame();
			}
		});
		newItemMenuItem_2.setText("&Load\tCtrl+L");



		new MenuItem(menu_1, SWT.SEPARATOR);
		newItemMenuItem_14 = new MenuItem(menu_1, SWT.NONE);
		newItemMenuItem_14.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent arg0) {
				Client.sendMsg(new UserPropertiesMsg(username));
				NetworkMsg msg = Client.getClientMsg();
				if (msg.getType()==Type.DBInfo)
					setUsernameProperties(((DBInfoMsg)msg).getInfo());
				UserProperties user = new UserProperties(shell, getUsernameProperties());
				user.open();
			}
		});
		newItemMenuItem_14.setText("&Username\tCtrl+U");
		newItemMenuItem_14.setAccelerator(SWT.CTRL | 'U');
		
		new MenuItem(menu_1, SWT.SEPARATOR);
		
		final MenuItem newItemMenuItem_11 = new MenuItem(menu_1, SWT.NONE);
		newItemMenuItem_11.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent arg0) {
				showRecords();
			}
		});
		newItemMenuItem_11.setText("&Records\tCtrl+R");
		newItemMenuItem_11.setAccelerator(SWT.CTRL | 'R');
		newItemMenuItem_13 = new MenuItem(menu_1, SWT.NONE);
		newItemMenuItem_13.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent arg0) {
				Client.sendMsg(new GameHistoryMsg(username));
				NetworkMsg msg = Client.getClientMsg();
				if (msg.getType()==Type.DBInfo)
					setPlayedPlGames(((DBInfoMsg)msg).getInfo());
				GameHistory gh = new GameHistory(plGames);
				gh.open();
			}
		});
		newItemMenuItem_13.setText("&Game History\tCtrl+G");
		newItemMenuItem_13.setAccelerator(SWT.CTRL | 'G');
		if (!isUserInDB()){
			newItemMenuItem_13.setEnabled(false);
			newItemMenuItem_14.setEnabled(false);
		}
		else{
			newItemMenuItem_13.setEnabled(true);
			newItemMenuItem_14.setEnabled(true);
		}
		/*if (!isNetwork){
			newItemMenuItem_13.setEnabled(true);
			newItemMenuItem_13.setEnabled(true);
		}
		else{
			newItemMenuItem_13.setEnabled(false);
			newItemMenuItem_14.setEnabled(false);
		}*/
		new MenuItem(menu_1, SWT.SEPARATOR);

		final MenuItem newItemMenuItem_3 = new MenuItem(menu_1, SWT.NONE);
		newItemMenuItem_3.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				exitGame();
			}
		});
		newItemMenuItem_3.setText("E&xit\tCtrl+X");
		newItemMenuItem_3.setAccelerator(SWT.CTRL | 'X');

		final Menu menu_3 = new Menu(actionsMenu);
		actionsMenu.setMenu(menu_3);

		final MenuItem newItemMenuItem_6 = new MenuItem(menu_3, SWT.NONE);
		newItemMenuItem_6.setAccelerator(SWT.CTRL | 'Z');
		newItemMenuItem_6.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				undo();
			}
		});
		newItemMenuItem_6.setText("&Undo\tCtrl+Z");

		final MenuItem newItemMenuItem_7 = new MenuItem(menu_3, SWT.NONE);
		newItemMenuItem_7.setAccelerator(SWT.CTRL | 'Y');
		newItemMenuItem_7.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				redo();
			}
		});
		newItemMenuItem_7.setText("&Redo\tCtrl+Y");

		final MenuItem newItemMenuItem_8 = new MenuItem(menu_3, SWT.NONE);
		newItemMenuItem_8.setAccelerator(SWT.CTRL | 'C');
		newItemMenuItem_8.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				commit(false);
			}	
		});
		newItemMenuItem_8.setText("&Commit\tCtrl+C");

		new MenuItem(menu_3, SWT.SEPARATOR);

		final MenuItem newItemMenuItem_9 = new MenuItem(menu_3, SWT.NONE);
		newItemMenuItem_9.setAccelerator(SWT.CTRL + 'D');
		newItemMenuItem_9.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				declare();
			}
		});
		newItemMenuItem_9.setText("&Declare\tCtrl+D");

		final MenuItem newItemMenuItem_10 = new MenuItem(menu_3, SWT.NONE);
		newItemMenuItem_10.setAccelerator(SWT.CTRL + 'M');
		newItemMenuItem_10.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent arg0) {
				showMission();
			}
		});
		newItemMenuItem_10.setText("Show &Mission\tCtrl+M");

		new MenuItem(menu_3, SWT.SEPARATOR);

		final MenuItem newItemMenuItem_12 = new MenuItem(menu_3, SWT.NONE);
		newItemMenuItem_12.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				ChangeHouseRulesDialog houseRulesDialog = new ChangeHouseRulesDialog(shell, game, gui);
				houseRulesDialog.open();
			}
		});
		newItemMenuItem_12.setText("House Rules");


		final MenuItem newSubmenuMenuItem_1 = new MenuItem(menu, SWT.CASCADE);
		newSubmenuMenuItem_1.setText("&Help");

		final Menu menu_2 = new Menu(newSubmenuMenuItem_1);
		newSubmenuMenuItem_1.setMenu(menu_2);

		final MenuItem newSubmenuMenuItem_2 = new MenuItem(menu_2, SWT.NONE);
		newSubmenuMenuItem_2.setText("&Tutorial\tCtrl+T");
		newSubmenuMenuItem_2.setAccelerator(SWT.CTRL | 'T');
		newSubmenuMenuItem_2.addSelectionListener(new SelectionAdapter(){
			public void widgetSelected(final SelectionEvent e){
				if((tutorial == null) || (tutorial.isEnded())){
					tutorial = new Tutorial(shell);
					tutorial.startTutorial();
				}
			}
		});

		final MenuItem newItemMenuItem_4 = new MenuItem(menu_2, SWT.NONE);
		newItemMenuItem_4.setAccelerator(SWT.CTRL | 'H');
		newItemMenuItem_4.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				showHelp();
			}
		});
		newItemMenuItem_4.setText("&Help\tCtrl+H");

		final MenuItem newItemMenuItem_5 = new MenuItem(menu_2, SWT.NONE);
		newItemMenuItem_5.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent arg0) {
				showAbout();
			}
		});
		newItemMenuItem_5.setText("&About");
	}

	protected void onlineGame() {
		NetworkGameDialog dialog = new NetworkGameDialog(RiskGUI.display.getActiveShell(), this);
		dialog.open();
	}

	/**
	 * @param e
	 */
	private void handleMouseDoubleClick(MouseEvent e) {
		// the player need to move soldiers before commit,
		// double click is not an option.
		if (game.status == GameStatus.NO_GAME) return;
		if (game.status == GameStatus.MOVE_SOLDIERS) return;
		Country currSelected = getSelected(e);
		boolean isAdd = currSelected != null;
		isAdd = isAdd && currSelected.getOwner() == game.getCurrentPlayer();
		isAdd = isAdd && game.getCurrentPlayer().getSoldiers() > 0;

		if(isAdd)
		{
			Label currLabel = getCountryTextLabel(currSelected);
			setLabelBackground(currLabel, true);
			// initially add one soldier to country in double click
			AddSoldierMove addMove = new AddSoldierMove(game.getCurrentPlayer(), currSelected, 1);
			if(game.getCurrentPlayer().addMove(addMove, isNetwork))
				addToLog(addMove.getBriefDo());

			// mark country somehow
			updateGUIMap();
			try {
				Thread.sleep(100);
				setLabelBackground(currLabel, false);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			if(game.getCurrentPlayer().CheckMovesRule()) commit(true);
			unselectCountry();
			return;
		}
		unselectCountry();
	}

	/**
	 * makes the moves for the current computer player
	 * @return true iff the player has accomplished his mission
	 */
	private boolean playComputerPlayer(){
		Player currPlayer = game.getCurrentPlayer();
		while(currPlayer.isComputer())
		{
			boolean hasNextMove = updateHasNextMove(currPlayer);
			while( hasNextMove ){
				GameMove next = currPlayer.getNextMove();
				lightCountriesForAI(next, true);
				if(currPlayer.addMove(next, isNetwork))
					addToLog(next.getBriefDo());
				updateGUIMap();
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				lightCountriesForAI(next,false);
				hasNextMove = updateHasNextMove(currPlayer);
			}
			// if computer has won the game
			// will commit moves and advance player
			if(commitAndAdvance())
			{
				updateGUIMap();
				return true;
			}
			currPlayer = game.getCurrentPlayer();
		}
		return false;
	}
	/**
	 * 
	 * @param currPlayer == AI computer player
	 * @return whether the computer player has a move
	 * to make, with regard to stage of game divide soldiers 
	 * or regular game phase
	 */
	private boolean updateHasNextMove(Player currPlayer) {
		//		if(currPlayer.CheckMovesRule()) return false;
		if(game.status == GameStatus.DIVIDE_SOLDIERS)
			return currPlayer.getSoldiers() > 0;
			else
				return currPlayer.hasNextMove();
	}

	public void addToLog(String string) {
		// Container.open may return null or empty string if X is pressed
		if(string != null && string.length() != 0)
		{
			textLog.setText(textLog.getText()+ string + "\r\n");
			textLog.setTopIndex(textLog.getLineCount());
			textLog.update();
		}
	}

	public void resetLog() {
		textLog.setText("");
	}

	/**
	 * Sets all GUI and game fields to a status of game over
	 * Updates record table
	 * Calls for a winning dialog
	 * @USE only for a winning game situation
	 * user declares a TRUE victory, or AI accomplishes mission
	 * @param actionsMenuSubItem
	 */
	private void endCurrentGame()
	{
		GameMngr.recordTable.addToRecordTable(game.getCurrentPlayer()); // records updated
		WinningDialog dialog = new WinningDialog(shell, game, gui); //good job, someone won!
		dialog.open();
		game.setGameOver(); // game is over
		game.setCommited(true); // moves are committed
		// map will not respond to additional player clicks
		game.status = GameStatus.NO_GAME;
		commitButton.setEnabled(false);
		this.isNetwork = false;
	}

	private void endCurrentGame(final MenuItem actionsMenuSubItem, Button commitButton)
	{
		GameMngr.recordTable.addToRecordTable(game.getCurrentPlayer()); // records updated
		if(!isNetwork){
			WinningDialog dialog = new WinningDialog(shell , game, gui); //good job, someone won!
			dialog.open();
		}
		// map will not respond to additional player clicks
		game.status = GameStatus.NO_GAME;
		if(actionsMenuSubItem != null)
			actionsMenuSubItem.setEnabled(false); // no actions can be done
		if(commitButton != null)
			commitButton.setEnabled(false);
		this.isNetwork = false;
	}

	/**
	 * Purpose: to commit moves and advance turn, add to log, in case player is 
	 * computer will also return true to indicate computer has won (in case of..)
	 * Set isFirst to false if all players have made their divideSoldiers
	 * Set isLast to false since its a new players turn
	 * Return: true iff player is computer and has won game
	 */
	public boolean commitAndAdvance() {
		Player curr = game.getCurrentPlayer();
		if(curr.isComputer() && curr.isMissionAccomplished())
			return true;
		game.commit();
		game.advancePlayerTurn();
		// don't display a defeated player
		if(!game.getCurrentPlayer().isDefeated() && !isNetwork)
			addToLog("\r\n" + game.getCurrentPlayer().getPlayerName() + ":\r\n");
		updateGUIMap();
		return false;
	}

	public void makePluginNewGame() {
		loadGameMngr();
		NewDialog dialog = new NewDialog(shell, game, playerColours);
		dialog.open();
		//		ChangeHouseRulesDialog houseDialog = new ChangeHouseRulesDialog(shell, game);
		//		houseDialog.open();
		if(game.getPlayers().size()>0){
			runGame();
			textLog.setText("");
			textLog.update();
			game.setReenforcement(game.getCurrentPlayer());
			updateGUIMap();
			addToLog(game.getCurrentPlayer().getPlayerName() + ":\n");
			if(game.getCurrentPlayer().isComputer()){
				if(playComputerPlayer()){
					if(isPlugin() || isRCP()){
						endCurrentGame();
					}else{
						endCurrentGame(null, commitButton);
					}
				}
			}
		}
	}

	/**
	 * 
	 */
	public void showAbout() {
		AboutDialog about = new AboutDialog(RiskGUI.display.getActiveShell());
		about.open();
	}

	/**
	 * 
	 */
	public void showHelp() {
		HelpDialog about = new HelpDialog(RiskGUI.display.getActiveShell());
		about.open();
	}

	/**
	 * 
	 */
	public void showRecords() {
		if (username=="" || !isUserInDB()){
			RecordsDialog dialog = new RecordsDialog(GameMngr.recordTable.toString(), RiskGUI.display.getActiveShell());
			dialog.open();
		}
		else{
			Client.sendMsg(new RecordsTableMsg());
			NetworkMsg msg = Client.getClientMsg();
			if (msg.getType()==Type.DBInfo)
				setRecordsTable(((DBInfoMsg)msg).getInfo());
			RecordsDialog dialog = new RecordsDialog(records, RiskGUI.display.getActiveShell());
			dialog.open();
		}
		//AutoDialogMessegaes.displayFeedbackMsg("Record Table", GameMngr.recordTable.toString(), Display.getCurrent().getActiveShell());
	}

	/**
	 * 
	 */
	public void exitGame() {
		RiskGUI.display.getActiveShell().close();
	}

	/**
	 * 
	 */
	public void undo() {
		if(game.getCurrentPlayer().canUndoLastMove()){
			if(game.getCurrentPlayer().undoMove(isNetwork)){
				addToLog(game.getCurrentPlayer().getRedoMoves().peek().getBriefUndo());
				updateGUIMap();
			}
		} else {
			AutoDialogMessegaes.displayErrorMsg("Error", "There are no move to undo, or last move was attack", RiskGUI.display.getActiveShell());
		}
	}

	/**
	 * 
	 */
	public void redo() {
		if(game.getCurrentPlayer().hasRedoMoves()){
			if(game.getCurrentPlayer().redoMove(isNetwork)){
				addToLog(game.getCurrentPlayer().getMoves().peek().getBriefDo());
				updateGUIMap();
			}
		} else {
			AutoDialogMessegaes.displayErrorMsg("Error", "There are no move to redo", RiskGUI.display.getActiveShell());
		}
	}

	/**
	 * 
	 */
	public void newGame() {
		loadGameMngr();
		NewDialog dialog = new NewDialog(RiskGUI.display.getActiveShell(), game, playerColours);
		dialog.open();
		if(game.getPlayers().size()>0){
			textLog.setText("");
			textLog.update();
			runGame();
			MessageDialog msg = new MessageDialog(shell,"Change House Rules",null,"Do you want to change the house rules of the game?",MessageDialog.QUESTION,new String[] {"Yes","No"},1);
			if(msg.open()==0){
				ChangeHouseRulesDialog houseRulesDialog = new ChangeHouseRulesDialog(shell, game, gui);
				houseRulesDialog.open();
			} 
			if(!isPlugin() && !isRCP()){
				actionsMenu.setEnabled(true);
				newItemMenuItem_1.setEnabled(true);
			}
			game.setReenforcement(game.getCurrentPlayer());
			updateGUIMap();
			addToLog(game.getCurrentPlayer().getPlayerName() + ":\n");
			if(game.getCurrentPlayer().isComputer()){
				if(playComputerPlayer()){
					if(isPlugin() || isRCP()){
						endCurrentGame();
					}else{
						endCurrentGame(actionsMenu, commitButton);
					}
				}
			}
		}
	}

	/**
	 * 
	 */
	public void loadGame() {
		LoadDialog load = new LoadDialog(RiskGUI.display.getActiveShell(),game, playerColours,gui, saveData);
		GameMngr tempGame = (GameMngr) load.open();
		updateGameMngr(tempGame);
	}

	/**
	 * @param tempGame
	 */
	public void updateGameMngr(GameMngr tempGame) {
		if(tempGame != null){
			game = tempGame;
		}
		if(game.getPlayers().size()>1){
			loadCountryMaps();
			loadCountryLabelMap();
			loadFlagColourImageMap();
			if(!isPlugin() && !isRCP()){
				actionsMenu.setEnabled(true);
				newItemMenuItem_1.setEnabled(true);
			}
			updateGUIMap();
		}
	}

	/**
	 * 
	 */
	public void showMission() {
		MissionDialog dialog;
		if(isNetwork){
			dialog = new MissionDialog("You " + getMe().getSecretMission().getMission(), RiskGUI.display.getActiveShell());
		}else{
			dialog = new MissionDialog("You " + game.getCurrentPlayer().getSecretMission().getMission(), RiskGUI.display.getActiveShell());
		}
		dialog.open();
		//		AutoDialogMessegaes.displayFeedbackMsg("Your Mission", "You " + game.getCurrentPlayer().getSecretMission().getMission(), Display.getCurrent().getActiveShell());
	}
	
	private Player getMe(){
		for(Player player : this.game.getPlayers()){
			if(player.isMe()){
				return player;
			}
		}
		return null;
	}

	/**
	 * 
	 */
	public void declare() {
		if (true){ //(game.getCurrentPlayer().isMissionAccomplished()) {
			if(isNetwork){
				Client.sendMsg(new WinniningMsg(game.getGameID()));
				WinningDialog dialog = new WinningDialog(shell , game, gui); //good job, someone won!
				dialog.open();
			}
			if(isPlugin() || isRCP()){
				endCurrentGame();
			}else{
				endCurrentGame(actionsMenu, commitButton);
			}
		} else {
			NotWinningDialog dialog = new NotWinningDialog(parent.getShell());
			dialog.open();
		}
	}

	/**
	 * commit - if isNumOfMoves is true than the player reached
	 *  the maximum number of moves in his turn so the message 
	 *  about the move phase should not appear
	 */
	public void commit(boolean isNumOfMoves) {
		if(isNetwork && !game.getCurrentPlayer().isMe())
			return;
		if((game.status == GameStatus.GAME_PLAY) && !isNumOfMoves) {
			MessageDialog msg = new MessageDialog(RiskGUI.display.getActiveShell(),"Move soldiers?",null,"Do you want to move soldiers before commit?",MessageDialog.QUESTION,new String[] {"Yes","No"},1);
			if(msg.open()==0){
				game.status = GameStatus.MOVE_SOLDIERS;
				updateGUIMap();
			} else {
				commitAndAdvance();
				updateGUIMap();
				if(game.getCurrentPlayer().isComputer()){
					if(playComputerPlayer()){
						if(isPlugin() || isRCP()){
							endCurrentGame();
						}else{
							endCurrentGame(actionsMenu, commitButton);
						}
					}
				}
				updateGUIMap();
				if(isNetwork){
					Client.sendMsg(new InformClients(game, "\r\n" + game.getCurrentPlayer().getPlayerName() + ":\r\n"));
				}
			}
		} 
		else {
			commitAndAdvance();
			if(game.getCurrentPlayer().isComputer()){
				if(playComputerPlayer()){
					if(isPlugin() || isRCP()){
						endCurrentGame();
					}else{
						endCurrentGame(actionsMenu, commitButton);
					}
				}
			}
			updateGUIMap();
			if(isNetwork){
				Client.sendMsg(new InformClients(game, "\r\n" + game.getCurrentPlayer().getPlayerName() + ":\r\n"));
			}
		}
	}

	/**
	 * 
	 */
	public void saveGame() {
		saveData.saveGame();
	}

	public void setMoveRuleOnAttack(boolean value) {
		moveRuleOnAttack = value;
	}

	public void lightCountriesForAI(GameMove move, boolean light) {

		if(move.getType().equals("ATTACKMOVE")){
			AttackMove attack = (AttackMove)move;
			Country attackingCountry = attack.getAttackingCountry();
			Country diffendingCountry = attack.getDefendingCountry();
			Label AttCountryLabel = getCountryTextLabel(attackingCountry);
			Label DifCountryLabel = getCountryTextLabel(diffendingCountry);
			setLabelBackground(AttCountryLabel, light);
			setLabelBackground(DifCountryLabel, light);
		} else if(move.getType().equals("ADDSOLDIERMOVE")) {
			AddSoldierMove add = (AddSoldierMove) move;
			Country country = add.getCountry();
			Label countryLable = getCountryTextLabel(country);
			setLabelBackground(countryLable, light);
		}
	}

	public static Point getNewPosition(Composite shell) {
		int xCoord = shell.getLocation().x + (shell.getBounds().width/10);
		int yCoord = shell.getLocation().y + (shell.getBounds().height/8);
		Point pos = new Point(xCoord,yCoord);
		return pos;
	}

	/**
	 * @return the game
	 */
	public GameMngr getGameMngr() {
		return game;
	}

	/**
	 * @param game the game to set
	 */
	public void setGame(GameMngr game) {
		this.game = game;
		for(Player player : game.getPlayers()){
			player.setGame(game);
		}
	}

	/**
	 * @return the game
	 */
	public GameMngr getGame() {
		return game;
	}

	/**
	 * @param username the username to set
	 */
	public static void setUsername(String username) {
		RiskGUI.username = username;
	}

	/**
	 * @return the username
	 */
	public static String getUsername() {
		return username;
	}
	/**
	 * @param records the record table string to set
	 */
	public void setRecordsTable(String records) {
		this.records = records;
	}

	/**
	 * @return the record table string
	 */
	public String getRecordsTable() {
		return records;
	}

	/**
	 * @param isNetwork the isNetwork to set
	 */
	public void setNetwork(boolean isNetwork) {
		this.isNetwork = isNetwork;
	}

	/**
	 * @return the isNetwork
	 */
	public boolean isNetwork() {
		return isNetwork;
	}

	public void setPlayedPlGames(String plGames) {
		this.plGames=plGames;
	}

	public String getPlayedGames() {
		return plGames;
	}

	/**
	 * @param userInDB the userInDB to set
	 */
	public static void setUserInDB(boolean userInDB) {
		RiskGUI.userInDB = userInDB;
	}

	/**
	 * @return the userInDB
	 */
	public static boolean isUserInDB() {
		return userInDB;
	}

	/**
	 * @param usernameProperties the usernameProperties to set
	 */
	public static void setUsernameProperties(String usernameProperties) {
		RiskGUI.usernameProperties = usernameProperties;
	}

	/**
	 * @return the usernameProperties
	 */
	public static String getUsernameProperties() {
		return usernameProperties;
	}
}
